package com.jihui.jihuipicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jihui.jihuipicturebackend.constant.UserConstant;
import com.jihui.jihuipicturebackend.exception.BusinessException;
import com.jihui.jihuipicturebackend.exception.ErrorCode;
import com.jihui.jihuipicturebackend.exception.ThrowUtils;
import com.jihui.jihuipicturebackend.manager.auth.StpKit;
import com.jihui.jihuipicturebackend.manager.upload.UserAvatarUpload;
import com.jihui.jihuipicturebackend.model.dto.file.UploadPictureResult;
import com.jihui.jihuipicturebackend.model.dto.user.UserAddRequest;
import com.jihui.jihuipicturebackend.model.dto.user.UserQueryRequest;
import com.jihui.jihuipicturebackend.model.dto.user.UserUpdateRequest;
import com.jihui.jihuipicturebackend.model.entity.Picture;
import com.jihui.jihuipicturebackend.model.entity.User;
import com.jihui.jihuipicturebackend.model.enums.UserRoleEnum;
import com.jihui.jihuipicturebackend.model.vo.PictureVO;
import com.jihui.jihuipicturebackend.model.vo.UserLoginVO;
import com.jihui.jihuipicturebackend.model.vo.UserVO;
import com.jihui.jihuipicturebackend.service.UserService;
import com.jihui.jihuipicturebackend.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.jihui.jihuipicturebackend.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author wu'ji'hui
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-12-30 15:21:15
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Resource
    private UserAvatarUpload userAvatarUpload;
    /**
     * 用户注册
     * @param userAccount 用户名
     * @param userPassword 密码
     * @param checkPassword 确认密码
     * @return
     */
    @Override
    public Long register(String userAccount, String userPassword, String checkPassword) {
        // 参数校验
        if(StrUtil.hasEmpty(userAccount, userPassword, checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名、密码、确认密码不能为空");
        }
        if(userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名长度不能小于4位");
        }
        if(userPassword.length() < 6 || checkPassword.length() < 6){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度不能小于6位");
        }
        if(userPassword.length() > 16){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度不能大于16位");
        }
        if(!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码输入不一致");
        }
        // 判断用户名是否存在
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.eq("userAccount", userAccount).eq("isDelete", 0);
        Long userCount = this.baseMapper.selectCount(userWrapper);
        if(userCount > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名已存在");
        }
        // 密码加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 保存用户信息
        User user = new User();
        user.setUserName("无名");
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserRole(UserRoleEnum.USER.getValue());
        if(!this.save(user)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "服务器错误，请稍后重试！");
        }
        // 返回用户id
        return user.getId();
    }

    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = "jihui";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }


    /**
     * 用户登录
     * @param userName 用户名
     * @param userPassword 密码
     * @param request 请求
     * @return 用户登录信息
     */
    @Override
    public UserLoginVO userLogin(String userName, String userPassword, HttpServletRequest request) {
        //1. 参数校验
        if(StrUtil.hasEmpty(userName, userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名、密码不能为空");
        }
        //2. 密码校验
        String encryptPassword = getEncryptPassword(userPassword);
        //3. 查询用户信息
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.eq("userAccount", userName).eq("userPassword", encryptPassword).eq("isDelete", 0);
        User user = this.baseMapper.selectOne(userWrapper);
        if(user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名或密码错误");
        }
        UserLoginVO userLoginVO = getUserLoginVO(user);
        // 4. 保存用户登录信息
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        // 5. 记录用户登录态到 Sa-token，便于空间鉴权时使用，注意保证该用户信息与 SpringSession 中的信息过期时间一致
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(USER_LOGIN_STATE, user);
        // 6. 返回用户信息
        return userLoginVO;
    }

    /**
     * 将用户信息转换为UserLoginVO对象
     * @param user 用户信息
     * @return UserLoginVO对象
     */
    @Override
    public UserLoginVO getUserLoginVO(User user) {
        if(ObjUtil.isEmpty(user)){
            return null;
        }
        UserLoginVO UserLoginVO = new UserLoginVO();
        BeanUtil.copyProperties(user, UserLoginVO);
        return UserLoginVO;
    }

    /**
     * 根据请求获取UserLoginVO对象
     * @param request 请求
     * @return UserLoginVO对象
     */
    @Override
    public User getUserLoginVOByRequest(HttpServletRequest request) {
        Object userLoginState = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userLoginState;
        if(ObjUtil.isEmpty(currentUser) || currentUser.getId() == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
        }
        //return currentUser;
        // 为了保证数据的强一致性，可以再到数据库中查询用户信息
        currentUser = this.baseMapper.selectById(currentUser.getId());
        return currentUser;
    }

    /**
     * 用户登出
     * @param request 请求
     * @return true成功，false失败
     */
    @Override
    public boolean userLoginOut(HttpServletRequest request) {
        Object userLoginState = request.getSession().getAttribute(USER_LOGIN_STATE);
        if(ObjUtil.isEmpty(userLoginState)){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
        }
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    /**
     * 根据查询条件获取用户列表
     * @param userList
     * @return
     */
    @Override
    public List<UserVO> getUserVOByQuery(List<User> userList) {
        if(CollUtil.isEmpty(userList)){
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    /**
     *
     * @param user
     * @return
     */
    public UserVO getUserVO(User user) {
        if(user == null){
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 根据查询条件构造查询条件
     * @param userQueryRequest
     * @return
     */
    public QueryWrapper<User> getUserQueryWrapper(UserQueryRequest userQueryRequest) {
        // 获取查询参数
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userRole = userQueryRequest.getUserRole();
        String userProfile = userQueryRequest.getUserProfile();
        // 获取分页参数
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();

        // 根据查询条件构造查询条件
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.eq(ObjUtil.isNotEmpty(id), "id", id)
                   .eq(StrUtil.isNotEmpty(userAccount), "userAccount", userAccount)
                   .like(StrUtil.isNotEmpty(userName), "userName", userName)
                   .eq(StrUtil.isNotEmpty(userRole), "userRole", userRole)
                   .like(StrUtil.isNotEmpty(userProfile), "userProfile", userProfile)
                   .orderBy(StrUtil.isNotEmpty(sortField),sortOrder.equals("ascend"), sortField);
        return userWrapper;
    }

    /**
     * 添加用户
     * @param userAddRequest
     * @return
     */
    @Override
    public boolean addUser(UserAddRequest userAddRequest) {
        // 构造用户对象
        User user = new User()
                .setUserName(userAddRequest.getUserName())
                .setUserAccount(userAddRequest.getUserAccount())
                .setUserPassword(getEncryptPassword("123456"))
                .setUserRole(userAddRequest.getUserRole())
                .setUserProfile(userAddRequest.getUserProfile());

        // 保存用户信息
        if(!this.save(user)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "服务器错误，请稍后重试！");
        }
        return true;
    }

    /**
     * 更新用户信息
     * @param userUpdateRequest
     * @return
     */
    @Override
    public boolean updateUser(UserUpdateRequest userUpdateRequest) {
        // 构造用户对象
        User user = new User()
                .setId(userUpdateRequest.getId())
                .setUserName(userUpdateRequest.getUserName())
                .setUserAvatar(userUpdateRequest.getUserAvatar())
                .setUserRole(userUpdateRequest.getUserRole())
                .setUserProfile(userUpdateRequest.getUserProfile());

        // 更新用户信息
        if(!this.updateById(user)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "服务器错误，请稍后重试！");
        }
        return true;
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @Override
    public boolean deleteUser(Long id) {
        // 根据id删除用户信息
        if(!this.removeById(id)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "服务器错误，请稍后重试！");
        }
        return true;
    }

    /**
     * 编辑用户信息
     * @param inputSource
     * @param userUpdateRequest
     * @return
     */
    @Override
    public UserVO editUser(Object inputSource, UserUpdateRequest userUpdateRequest) {
        // 1.参数校验，由于模板中有参数校验，因此此处不做重复校验
        // 2.根据id判断是新用户还是更新用户
        Long userId = null;
        if(ObjUtil.isNotEmpty(userUpdateRequest)){
            userId = userUpdateRequest.getId();
        }
        // 若是跟新用户，查询信息是否存在
        if(userId!= null){
            boolean exists = this.lambdaQuery()
                    .eq(User::getId, userId)
                    .exists();
            ThrowUtils.throwIf(!exists, ErrorCode.NOT_FOUND_ERROR, "用户信息不存在");
        }

        // 上传图片，得到信息
        // 按照用户 id 划分目录
        String uploadPathPrefix = String.format("Avatar/%s", userId);
        // 上传图片
        UploadPictureResult uploadUserAvatar = userAvatarUpload.uploadPicture(inputSource, uploadPathPrefix);

        // 3.构造用户对象
        User user = new User();
        user.setUserAvatar(uploadUserAvatar.getUrl());
        if(userId != null){
            user.setId(userId);
            user.setEditTime(new Date());
        }
        boolean result = this.saveOrUpdate(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "用户信息保存失败");
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }
}




